#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
#include "/home/lhr/http-server/dbManager.hpp"
#include "/home/lhr/http-server/Util.hpp"

int main()
{
    Json::Value result;
    std::string reqParam;
    Util::GetReqParam(reqParam);

    std::string queryParam;
    std::string queryValue;
    Util::CutString(reqParam, queryParam, queryValue, "=");
    queryValue = Util::UrlDecode(queryValue);

    DBManager &db = DBManager::GetInstance();
    std::vector<Json::Value> articles;
    bool found = false;

    // 检查请求参数中是否包含特定的查询标题
    if (queryParam == "query" && !queryValue.empty())
    {
        // 查询指定标题的文章
        articles = db.searchArticle(queryValue);
        if (!articles.empty())
        {
            found = true;
        }
    }

    // 如果未找到特定文章，返回所有文章
    if (!found)
    {
        articles = db.getAllArticles();
    }

    // 构建 JSON 响应
    result["found"] = found;
    for (const auto &article : articles)
    {
        result["articles"].append(article);
    }

    std::string http_resBody = result.toStyledString();
    // 向管道输出cgi请求的http响应
    std::string http_res;
    http_res += "HTTP/1.0 200 OK\r\n";
    http_res += "Content-Type: application/json\r\n";
    http_res += "Content-Length: ";
    http_res += std::to_string(http_resBody.length());
    http_res += "\r\n";
    http_res += "\r\n";
    http_res += http_resBody;

    std::cout << http_res;
    return 0;
}
